#include<assert.h>
#include<errno.h>
#include<fcntl.h>
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>

sem_t * CreateSemaphore( const char * inName, const int inStartingCount );  
typedef struct{
	sem_t *lock;
	int num;
}STRUCT;

void test(void *obj){
	STRUCT *point = (STRUCT *)obj;
	sem_t *semlock =point->lock;
	sem_wait(semlock);
	FILE *f = fopen("04.POSIXsemaphore.o","a");
	if(f == NULL)
		printf("fopen is wrong\n");
	printf("sem_wait %d\n",point->num);
	int j = 0;
	for(j=0;j<30;j++)
		fprintf(f,"%c1111111111\n",'a'+point->num);
	fclose(f);
	sem_post(semlock);

	return;
}

int main(){
	pthread_t pid[20];
	int ret,i = 0;
	STRUCT obj[13];
	sem_t *semlock;
	semlock = CreateSemaphore("hello",1);
	for(i=0;i<10;i++){
		obj[i].num = i;
		obj[i].lock = semlock;
		ret = pthread_create(&pid[i],NULL,(void*)test,&obj[i]);

		if(ret!=0){
			printf("create thread wroing %d!!\n",i);
			return 0;
		}
	}
	sem_close(semlock);
	//sem_ulink("hello");
	for(int i=0;i<10;i++)
			pthread_join(pid[i],NULL);
		
	return 0;
}
sem_t * CreateSemaphore( const char * inName, const int inStartingCount )  
{  
    sem_t * semaphore = sem_open( inName, O_CREAT, 0644, inStartingCount );  
      
    //  
    if( semaphore == SEM_FAILED )  
    {  
        switch( errno )  
        {  
            case EEXIST:  
                printf( "Semaphore with name '%s' already exists.\n", inName );  
                break;  
                  
            default:  
                printf( "Unhandled error: %d.\n", errno );  
                break;  
        }  
          
        //  
        assert(0);  
        return SEM_FAILED;  
    }  
      
    //  
    return semaphore;  
}  
  
